package com.tensai.study.基础.数据结构.HashMap.线程安全;

import java.util.HashMap;

/**
 * 我觉得本测试类，并不能说明Hash存在线程安全问题
 *
 * @author Tensai
 * 2019/3/27
 */
public class HashMapTest {

    //  使用ConcurrentHashMap可运行正常
    //final static ConcurrentHashMap<String, String> ch = new ConcurrentHashMap<>();
    private final static HashMap<String, String> ch = new HashMap<>();

    //  运行的线程
    public static class R implements Runnable {

        private String end;

        R(String end) {
            super();
            this.end = end;
        }

        @Override
        public void run() {
            while (!this.end.equals(ch.get("end"))) {
                System.out.print(this.end + " ");
            }
            System.out.println("\n" + this.end + ": is End!");
        }

    }

    public static void main(String[] args) {
        //  启动线程
        for (int i = 0; i < 100; i++) {
            new Thread(new R(String.valueOf(i))).start();
        }
        new Thread(() -> {
            int j = 0;
            while (j < 100) {
                ch.put("end", String.valueOf(j));
                //  让其他线程有执行的机会
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                j++;
            }
        }).start();

    }

}